﻿using LightCAD.Core;
using LightCAD.Core.Elements;
using LightCAD.MathLib;
using System;
using System.Drawing;
using System.Xml.Linq;
using Teigha.DatabaseServices;
using Teigha.Geometry;
using Teigha.Runtime;

namespace LightCAD.ImpExpDwg
{
    public class DwgReader
    {
        public static LcDocument Import(string filePath)
        {
            //注册码加载
            Teigha.Runtime.Services.odActivate(ActivationData.userInfo, ActivationData.userSignature);
            LcDocument lcDocument = new LcDocument();
            Services services = new Services();
            {

                ReaderWriteException.Init();
                lcDocument.Initialize();
                lcDocument.InsertPoint = new Vector2();

                Database database = UtilityClass.ReadDwgFile(filePath);
                if (database == null)
                {
                    return lcDocument;
                }
                lcDocument.FilePath = filePath;
                using (var tran = database.TransactionManager.StartTransaction())
                {
                    BlockTable blockTable = database.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable;
                    var modelSpace = blockTable[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForRead) as BlockTableRecord;
                    List<ObjectId> objectIds = new List<ObjectId>();
                    #region 图层处理
                    LayerTable layerTable = (LayerTable)database.LayerTableId.GetObject(OpenMode.ForRead);
                    foreach (var layerId in layerTable)
                    {
                        LayerTableRecord layerTableRecord = (LayerTableRecord)layerId.GetObject(OpenMode.ForRead);
                        LcLayer LcLayer = lcDocument.CreateObject<LcLayer>();
                        LcLayer.Description = layerTableRecord.Description;
                        if (layerTableRecord.Id == database.Clayer)
                            LcLayer.IsStatus = true;
                        else
                            LcLayer.IsStatus = false;
                        LcLayer.Name = layerTableRecord.Name;
                        LcLayer.IsOff = layerTableRecord.IsOff;
                        LcLayer.IsFrozen = layerTableRecord.IsFrozen;
                        LcLayer.IsLocked = layerTableRecord.IsLocked;
                        var colorValue = (uint)layerTableRecord.Color.ColorValue.ToArgb();
                        LcLayer.Color = colorValue;
                        LcLayer.LineTypeId = 1;
                        LcLayer.LineWeight = Core.LineWeight.ByLayer;
                        LcLayer.Transparency = 0;
                        //LcLayer.PrintStyle = "Color" + i;
                        //LcLayer.IsPrint = true;
                        LcLayer.ViewportVisibilityDefault = 0;
                        LcLayer.Description = "";
                        lcDocument.Layers.Add(LcLayer);
                    }
                    #endregion
                    #region 线型
                    LinetypeTable acLinTbl = database.LinetypeTableId.GetObject(OpenMode.ForRead) as LinetypeTable;

                    foreach (var lineTypeId in acLinTbl)
                    {
                        LinetypeTableRecord linetype = (LinetypeTableRecord)lineTypeId.GetObject(OpenMode.ForRead);
                        var numDashes = linetype.NumDashes;
                        var PatternLength = linetype.PatternLength;
                        List<bool> IsUcsOrienteds = new List<bool>();
                        List<int> numbers = new List<int>();
                        List<Vector2d> offsets = new List<Vector2d>();
                        List<double> rotations = new List<double>();
                        List<double> scales = new List<double>();
                        List<ObjectId> styleIds = new List<ObjectId>();
                        List<string> texts = new List<string>();
                        List<double> lengths = new List<double>();
                        for (int i = 0; i < numDashes; i++)
                        {
                            var ucs = linetype.ShapeIsUcsOrientedAt(i);
                            IsUcsOrienteds.Add(ucs);
                            var number = linetype.ShapeNumberAt(i);
                            numbers.Add(number);
                            var off = linetype.ShapeOffsetAt(i);
                            offsets.Add(off);
                            var rotation = linetype.ShapeRotationAt(i);
                            rotations.Add(rotation);
                            var scale = linetype.ShapeScaleAt(i);
                            scales.Add(scale);
                            ObjectId styleId = linetype.ShapeStyleAt(i);
                            styleIds.Add(styleId);
                            string text = linetype.TextAt(i);
                            texts.Add(text);
                            var len = linetype.DashLengthAt(i);
                            lengths.Add(len);


                        }


                    }
                    #endregion
                    #region 组的处理
                    DBDictionary groups = (DBDictionary)database.GroupDictionaryId.GetObject(OpenMode.ForRead);
                    // 遍历所有的组
                    foreach (DBDictionaryEntry entry in groups)
                    {
                        Group group = (Group)entry.Value.GetObject(OpenMode.ForRead);
                        ObjectId[] ids = group.GetAllEntityIds();
                        List<LcElement> elements = new List<LcElement>();
                        // 遍历组下的图元
                        foreach (ObjectId oid in ids)
                        {
                            Entity entity = oid.GetObject(OpenMode.ForRead) as Entity;
                            var lcElement = ConvertToLightCAD.ConverEntityToLcElement(lcDocument, entity);
                            elements.Add(lcElement);
                        }
                        objectIds.AddRange(ids);
                        var lcGroup = lcDocument.CreateObject<LcGroup>();
                        lcGroup.Name = group.Name;
                        lcGroup.Description = group.Description;
                        foreach (var element in elements)
                        {
                            lcGroup.InsertElement(element);
                        }
                        lcDocument.ModelSpace.InsertElement(lcGroup);
                    }

                    #endregion
                    #region 块定义
                    foreach (var blockId in blockTable)
                    {
                        if (blockId == blockTable[BlockTableRecord.ModelSpace])
                        {
                            continue;
                        }
                        BlockTableRecord block = blockId.GetObject(OpenMode.ForRead) as BlockTableRecord;
                        var lcBlock = lcDocument.CreateObject<LcBlock>();
                        foreach (var objectId in block)
                        {
                            try
                            {
                                if (objectIds.Contains(objectId)) { continue; }
                                Entity? entity = objectId.GetObject(OpenMode.ForRead) as Entity;
                                if (entity == null) continue;
                                var lcElement = ConvertToLightCAD.ConverEntityToLcElement(lcDocument, entity);
                                if (lcElement == null) continue;
                                lcBlock.InsertElement(lcElement);
                            }
                            catch (System.Exception ex)
                            {
                                ReaderWriteException.Add(ex);
                            }
                        }
                        lcBlock.Name = block.Name;
                        lcDocument.Blocks.Add(lcBlock);
                    }
                    #endregion
                    #region 元素处理
                    foreach (var objectId in modelSpace)
                    {
                        try
                        {
                            if (objectIds.Contains(objectId)) { continue; }
                            Entity? entity = objectId.GetObject(OpenMode.ForRead) as Entity;
                            if (entity == null) continue;
                            var lcElement = ConvertToLightCAD.ConverEntityToLcElement(lcDocument, entity);
                            if (lcElement == null) continue;
                            lcDocument.ModelSpace.InsertElement(lcElement);
                        }
                        catch (System.Exception ex)
                        {
                            ReaderWriteException.Add(ex);
                        }
                    }
                    #endregion

                }
                ReaderWriteException.OutputMessage();
            }
            return lcDocument;
        }
    }
}